<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <button id="save">存储 Cookie</button>
    <button id="get">获取 Cookie</button>
    <p>
        <button id="edit" >修改 Cookie </button>
    </p>
</body>
<script>
   // 使用和学习 cookie 必须要使用带有服务器环境的编辑器打开  

    // cookie 是跟服务器有关  域名挂钩  域名区别  (www.taobao.com)

    // cookie 的创建  
    // 1. cookie 的存取都依赖于 document.cookie 
    // 2. cookie是以键值对(key=value)形式存在的字符串  {key:value}   key=value 
    // 3. cookie 存储的时候是一条一条的的存的 (每条数据之前用"; " 分隔)

    var save = document.getElementById("save")
    var get = document.getElementById("get")
    var edit = document.querySelectorAll("#edit")[0]



    save.onclick = function(){
        var date = new Date();
        date.setDate(date.getDate()+7)
        console.log(date)
        document.cookie = "user=zuozuomu;expires="+date.toUTCString()+";path=/";
        document.cookie = "pass=abc123;expires="+date.toUTCString()+";path=/";
        document.cookie = "phone=18012341234;expires="+date.toUTCString()+";path=/";
        document.cookie = "email=zkl.qq.com;expires="+date.toUTCString()+";path=/";
    }

    // 获取 cookie 
    // 封装 getCookie(key)
    get.onclick = function(){
        var cookie = document.cookie
        console.log(cookie)
        if(cookie){
            var obj = {}
            var arr =  cookie.split("; ")
            console.log(arr)
            for(var i=0;i<arr.length;i++){
                var item = arr[i]
                console.log(item)
                var key = item.split("=")[0]
                var value = item.split("=")[1]
                // obj.key = value   key 是一个  字符串key 不是变量 key
                obj[key] = value 
            }
            console.log(obj)
        }
    }

    // 修改 cookie  
    // 通过对应的 键值  去修改对应的 value 值
    // 重新赋值
    edit.onclick = function(){
        var date = new Date();
        date.setDate(date.getDate()+7)
        console.log(date)
        document.cookie = "user=xiaohu;expires="+date.toUTCString()+";path=/";
        document.cookie = "pass=qwer12;expires="+date.toUTCString()+";path=/";
        document.cookie = "phone=201820182018;expires="+date.toUTCString()+";path=/";
        document.cookie = "email=rng.qq.com;expires="+date.toUTCString()+";path=/"; 
    }
</script>
</html>